/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package cliente;

import java.awt.Button;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;

/**
 *
 * @author sala_a
 */
public class ClienteGUI extends javax.swing.JFrame {

    /**
     * Creates new form ClienteGUI
     */
    
    public class ThreadEsclavo implements Runnable{

    private Maquina maquina;
    
    public ThreadEsclavo(Maquina maquina) {
        this.maquina = maquina;
    }
        
    @Override
    public void run() {
        System.out.println("Hilo iniciado: " + Thread.currentThread().getName());
        VisorMaquinaGUI visorMaquinaGUI = new VisorMaquinaGUI();
        visorMaquinaGUI.setName(maquina.getNumeroMaquina());
        visorMaquinaGUI.setVisible(true);
        try {
            String info = "Máquina número: " + maquina.getNumeroMaquina() + "\n" + "IP: " +maquina.getIp();
            visorMaquinaGUI.mostrarInfoDinamica(info);
            visorMaquinaGUI.mostrarInfoEstatica(info);
            //Información estática
            if (maquina.isInformarSO()) {
                info = cliente.informarSO(maquina.getIp());
                System.out.println(info);
                visorMaquinaGUI.mostrarInfoEstatica(info);
            }
            if (maquina.isInfoEstaticaCpu()) {
                info = cliente.infoEstaticaCpu(maquina.getIp());
                System.out.println(info);
                visorMaquinaGUI.mostrarInfoEstatica(info);
            }
            //Información dinámica
            if (maquina.getTiempoTotal() != 0 && maquina.getFrecuencia() != 0) {
                for (int i=0 ; i<maquina.getFrecuencia() ; i++) {
                    if (maquina.isInfoDiscoArchivos()) {
                        info = cliente.infoDiscoArchivos(maquina.getIp());
                        System.out.println(info);
                        visorMaquinaGUI.mostrarInfoDinamica(info);
                    }
                    if (maquina.isInfoHilosProcesos()) {
                        info = cliente.infoHilosProcesos(maquina.getIp());
                        System.out.println(info);
                        visorMaquinaGUI.mostrarInfoDinamica(info);
                    }
                    if (maquina.isInfoMemoria()) {
                        info = cliente.infoMemoria(maquina.getIp());
                        System.out.println(info);
                        visorMaquinaGUI.mostrarInfoDinamica(info);
                    }
                    if (maquina.isInformarCpu()) {
                        info = cliente.informarCpu(maquina.getIp());
                        System.out.println(info);
                        visorMaquinaGUI.mostrarInfoDinamica(info);
                    }
                    visorMaquinaGUI.repaint();
                    Thread.sleep(maquina.getTiempoTotal()*1000/maquina.getFrecuencia());
                }
            }
        } catch (InterruptedException ex) {
            visorMaquinaGUI.mostrarInfoDinamica("Esclavo no disponible");
        } catch (Exception ex) {
            visorMaquinaGUI.mostrarInfoDinamica("Esclavo no disponible");
        }
            System.out.println("Hilo finalizado: " + Thread.currentThread().getName());
    }
}
    
    
    Cliente cliente;
    int numMaquinas;
    public static Map<String, Maquina> configuracionesMaquinas;
    
    public ClienteGUI() {
        initComponents();
        cliente = new Cliente();
        if (cliente.conectarServidor()) {
            numMaquinas = cliente.getEsclavos().size();
            configuracionesMaquinas = new HashMap<>();
            int j=0, x=20, y=50;
        
            for (int i=0 ; i<numMaquinas ; i++) {
                if (j==6) {
                    y+=80;
                    x = 20;
                    j=0;
                }
                final String ip = getIP(i);
                JButton buttonMaquina = new JButton("Máquina " + (i+1));
                final String num = new String(Integer.toString(i+1));
                buttonMaquina.setBounds(x, y, 100, 60);
                buttonMaquina.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent ae) {
                        MaquinaGUI maquinaJFrame = new MaquinaGUI();
                        maquinaJFrame.setName(num);
                        maquinaJFrame.setIP(ip);
                        
                        maquinaJFrame.setVisible(true);
                    }
                });
                add(buttonMaquina);
                j++;
                x+=120;
            }
        } else {
            //TODO: Mostrar mensaje de conexión fallida
        }
    }
    
    public String getIP(int n) {
        int id = 0;
        for (Map.Entry<String,Boolean> entry : cliente.getEsclavos().entrySet()) {
            if (id == n)
                return entry.getKey();
            id++;
        }
        return null;
    }
    
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jButton3 = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        consultarButton = new javax.swing.JButton();
        consultarDinamicaButton = new javax.swing.JButton();
        consultarEstaticaButton = new javax.swing.JButton();

        jButton3.setText("jButton2");

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
        jLabel1.setText("VISOR DE MÁQUINAS");

        consultarButton.setText("Consultar");
        consultarButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                consultarButtonActionPerformed(evt);
            }
        });

        consultarDinamicaButton.setText("Consultar Información Dinámica");
        consultarDinamicaButton.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                consultarDinamicaButtonMouseClicked(evt);
            }
        });

        consultarEstaticaButton.setText("Consultar Información Estática");
        consultarEstaticaButton.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                consultarEstaticaButtonMouseClicked(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(consultarDinamicaButton)
                .addGap(48, 48, 48)
                .addComponent(consultarButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 51, Short.MAX_VALUE)
                .addComponent(consultarEstaticaButton)
                .addContainerGap())
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jLabel1)
                .addGap(160, 160, 160))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 224, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(consultarButton)
                    .addComponent(consultarDinamicaButton)
                    .addComponent(consultarEstaticaButton))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void consultarButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_consultarButtonActionPerformed
            List<Thread> hilos = new ArrayList<>();
            
            Iterator<Maquina> itMaquina = configuracionesMaquinas.values().iterator();
            while (itMaquina.hasNext()) {
                Maquina maquina = itMaquina.next();
                Thread hilo = new Thread(new ThreadEsclavo(maquina), maquina.getNumeroMaquina());
                hilos.add(hilo);
            }

            if (!hilos.isEmpty()) {
                for (Thread h : hilos) {
                    h.start();
                }
                for (Thread h : hilos) {
                    try {
                        h.join();
                    } catch (InterruptedException ex) {
                        System.out.println("Esclavo no disponible");
                    }
                }
            }
    }//GEN-LAST:event_consultarButtonActionPerformed

    //Información dinámica
    private void consultarDinamicaButtonMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_consultarDinamicaButtonMouseClicked
        int i = 1;
        Iterator it = cliente.getEsclavos().keySet().iterator();
        while (it.hasNext()) {
            try {
                VisorMaquinaGUI visorMaquinaGUI = new VisorMaquinaGUI();
                visorMaquinaGUI.setName(Integer.toString(i));
                visorMaquinaGUI.setVisible(true);
                String ip = (String)it.next();
                cliente.getEsclavos().get(ip);
                visorMaquinaGUI.mostrarInfoDinamica(cliente.infoDiscoArchivos(ip));
                visorMaquinaGUI.mostrarInfoDinamica(cliente.infoHilosProcesos(ip));
                visorMaquinaGUI.mostrarInfoDinamica(cliente.infoMemoria(ip));
                visorMaquinaGUI.mostrarInfoDinamica(cliente.informarCpu(ip));
            } catch (Exception ex) {
                Logger.getLogger(ClienteGUI.class.getName()).log(Level.SEVERE, null, ex);
            }
            i++;
        }
    }//GEN-LAST:event_consultarDinamicaButtonMouseClicked

    //Información estática
    private void consultarEstaticaButtonMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_consultarEstaticaButtonMouseClicked
        int i=1;
        Iterator it = cliente.getEsclavos().keySet().iterator();
        while (it.hasNext()) {
            try {
                VisorMaquinaGUI visorMaquinaGUI = new VisorMaquinaGUI();
                visorMaquinaGUI.setName(Integer.toString(i));
                visorMaquinaGUI.setVisible(true);
                String ip = (String)it.next();
                cliente.getEsclavos().get(ip);
                visorMaquinaGUI.mostrarInfoEstatica(cliente.informarSO(ip));
                visorMaquinaGUI.mostrarInfoEstatica(cliente.infoEstaticaCpu(ip));
            } catch (Exception ex) {
                Logger.getLogger(ClienteGUI.class.getName()).log(Level.SEVERE, null, ex);
            }
            i++;
        }
    }//GEN-LAST:event_consultarEstaticaButtonMouseClicked

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(ClienteGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ClienteGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ClienteGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ClienteGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new ClienteGUI().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton consultarButton;
    private javax.swing.JButton consultarDinamicaButton;
    private javax.swing.JButton consultarEstaticaButton;
    private javax.swing.JButton jButton3;
    private javax.swing.JLabel jLabel1;
    // End of variables declaration//GEN-END:variables
}
